package jgjc.config;


import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 〈一句话功能简述〉<br>
 *
 * @author hanxinghua
 * @create 2020/6/29
 * @since 1.0.0
 */
@Configuration
@WebFilter(filterName = "CorsFilter", urlPatterns = {"/**"})
public class CorsFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException
    {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        // 响应标头指定 指定可以访问资源的URI路径
        res.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        // 指示的请求的响应是否可以暴露于该页面。当true值返回时它可以被暴露
        res.setHeader("Access-Control-Allow-Credentials", "true");
        //响应标头指定响应访问所述资源到时允许的一种或多种方法
        res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        //设置 缓存可以生存的最大秒数
        res.setHeader("Access-Control-Max-Age", "3600");
        //自定义 可以被访问的响应头
        res.setHeader("Access-Control-Allow-Headers", "*");
        if ("OPTIONS".equals(req.getMethod())) {
            res.setStatus(res.SC_OK);
            return;
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }

}
